// 响应数据类型定义
export interface ApiResponse<T = unknown> {
  code?: number;
  success: boolean;
  message: string;
  data: T;
}

// 请求配置类型
export interface RequestConfig {
  method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
  headers?: Record<string, string>;
  body?: unknown;
  params?: Record<string, unknown>;
  timeout?: number;
}

// 请求错误类型
export class RequestError extends Error {
  public override name = "RequestError";

  constructor(
    public status: number,
    public override message: string,
    public data?: unknown
  ) {
    super(message);
  }
}

/**
 * 获取请求头
 */
function getHeaders(): Record<string, string> {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
  };

  // 从用户store获取token
  // 只有在客户端环境下(import.meta.client为true)才执行下面的代码，用于区分服务端和客户端，防止在服务端渲染时访问浏览器特有的对象或方法
  if (import.meta.client) {
    const userStore = useUserStore();
    console.log(userStore);

    if (userStore.token) {
      headers["Authorization"] = `Bearer ${userStore.token}`;
    }
  }

  return headers;
}

/**
 * 处理响应
 */
async function handleResponse<T>(response: Response): Promise<ApiResponse<T>> {
  if (!response.ok) {
    let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
    let errorData: unknown = null;

    try {
      const errorText = await response.text();
      if (errorText) {
        const errorJson = JSON.parse(errorText);
        errorMessage = errorJson.message || errorMessage;
        errorData = errorJson;
      }
    } catch {
      // 如果解析失败，使用默认错误信息
    }

    throw new RequestError(response.status, errorMessage, errorData);
  }

  const contentType = response.headers.get("content-type");
  if (contentType && contentType.includes("application/json")) {
    return await response.json();
  } else {
    return {
      // code: 200,
      success: true,
      message: "success",
      data: await response.text(),
    } as ApiResponse<T>;
  }
}

/**
 * 构建URL
 */
function buildUrl(url: string, params?: Record<string, unknown>): string {
  if (!params || Object.keys(params).length === 0) {
    return url;
  }

  const searchParams = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    console.log(key, value, "key, value");
    if (value !== null && value !== undefined && value !== "") {
      searchParams.append(key, String(value));
    }
  });

  const queryString = searchParams.toString();
  return queryString ? `${url}?${queryString}` : url;
}

/**
 * 基础请求方法
 */
async function request<T = unknown>(
  url: string,
  config: RequestConfig = {}
): Promise<ApiResponse<T>> {
  const {
    method = "GET",
    headers = {},
    body,
    params,
    timeout = 10000,
  } = config;

  // 合并请求头
  const requestHeaders = {
    ...getHeaders(),
    ...headers,
  };
  console.log(params, "params");

  // 构建完整URL
  const fullUrl = buildUrl(url, params);

  // 创建请求配置
  const requestConfig: RequestInit = {
    method,
    headers: requestHeaders,
  };

  // 添加请求体
  if (body && method !== "GET") {
    if (body instanceof FormData) {
      // 如果是FormData，删除Content-Type让浏览器自动设置
      delete requestHeaders["Content-Type"];
      requestConfig.body = body;
    } else {
      requestConfig.body = JSON.stringify(body);
    }
  }

  // 创建AbortController用于超时控制
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);
  requestConfig.signal = controller.signal;

  try {
    const response = await fetch(fullUrl, requestConfig);
    clearTimeout(timeoutId);
    return await handleResponse<T>(response);
  } catch (error) {
    clearTimeout(timeoutId);

    if (error instanceof RequestError) {
      throw error;
    }

    if (error instanceof Error) {
      if (error.name === "AbortError") {
        throw new RequestError(408, "请求超时");
      }
      throw new RequestError(0, error.message);
    }

    throw new RequestError(0, "网络错误");
  }
}

/**
 * GET请求
 */
export function get<T = unknown>(
  url: string,
  params?: Record<string, unknown>,
  config?: Omit<RequestConfig, "method" | "params">
): Promise<ApiResponse<T>> {
  return request<T>(url, { ...config, method: "GET", params });
}

/**
 * POST请求
 */
export function post<T = unknown>(
  url: string,
  body?: unknown,
  config?: Omit<RequestConfig, "method" | "body">
): Promise<ApiResponse<T>> {
  return request<T>(url, { ...config, method: "POST", body });
}

/**
 * PUT请求
 */
export function put<T = unknown>(
  url: string,
  body?: unknown,
  config?: Omit<RequestConfig, "method" | "body">
): Promise<ApiResponse<T>> {
  return request<T>(url, { ...config, method: "PUT", body });
}

/**
 * DELETE请求
 */
export function del<T = unknown>(
  url: string,
  config?: Omit<RequestConfig, "method">
): Promise<ApiResponse<T>> {
  return request<T>(url, { ...config, method: "DELETE" });
}

/**
 * PATCH请求
 */
export function patch<T = unknown>(
  url: string,
  body?: unknown,
  config?: Omit<RequestConfig, "method" | "body">
): Promise<ApiResponse<T>> {
  return request<T>(url, { ...config, method: "PATCH", body });
}

/**
 * 文件上传
 */
export function upload<T = unknown>(
  url: string,
  file: File | FormData,
  config?: Omit<RequestConfig, "method" | "body">
): Promise<ApiResponse<T>> {
  const body =
    file instanceof FormData
      ? file
      : (() => {
          const formData = new FormData();
          formData.append("file", file);
          return formData;
        })();

  return request<T>(url, { ...config, method: "POST", body });
}

// 导出默认请求实例
export default {
  get,
  post,
  put,
  delete: del,
  patch,
  upload,
  request,
};
